package cn.lichenfei.fxui.controls.skin;

import cn.lichenfei.fxui.controls.CFSwitch;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.beans.property.BooleanProperty;
import javafx.geometry.Pos;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;


public class CFSwitchSkin extends CFLabelSkin<CFSwitch> {

    private final Rectangle back;
    private final Circle circle;
    private final StackPane box;
    //
    private final double size = 20;
    private final TranslateTransition TT;

    public CFSwitchSkin(CFSwitch control) {
        super(control);
        back = new Rectangle();
        circle = new Circle();
        box = new StackPane(back, circle);
        double backSize = size - 6;
        back.setHeight(backSize);
        back.setWidth(size * 2);
        back.setArcHeight(backSize);
        back.setArcWidth(backSize);
        circle.setRadius(size / 2);
        StackPane.setAlignment(circle, Pos.CENTER_LEFT);
        TT = new TranslateTransition(Duration.millis(200), circle);
        //
        textProperty().bind(control.textProperty());
        setGraphic(box);

        initEvent();
    }

    private void initEvent() {
        CFSwitch cfSwitch = getSkinnable();
        BooleanProperty sp = cfSwitch.selectedProperty();
        circle.setTranslateX(sp.get() ? size : 0);
        cfSwitch.setOnMouseClicked(event -> {
            if (Animation.Status.RUNNING.equals(TT.getStatus())) {
                return;
            }
            sp.set(!sp.get());
        });
        // 监听是否选中，启动动画
        sp.addListener((observable, oldValue, newValue) -> {
            TT.setInterpolator(Interpolator.EASE_BOTH);
            TT.setToX(newValue ? size : 0);
            TT.setFromX(newValue ? 0 : size);
            TT.play();
        });
        //颜色绑定
        circle.fillProperty().addListener((observable, oldValue, newValue) -> {
            Color color = (Color) newValue;
            back.setFill(color.deriveColor(1, 1, 1, 0.4));
        });
        circle.fillProperty().bind(cfSwitch.fillColorProperty());
    }
}
